package com.xingxue.logistics;

import com.xingxue.logistics.common.annotation.NeedLogin;
import com.xingxue.logistics.common.annotation.UnLogin;
import com.xingxue.logistics.common.vo.Constant;

import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 * @author Kris at 2018/9/30 14:59
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登陆拦截校验规则：
     * 1.有@NeedLogin注解的，一律校验
     * 2.没有@NeedLogin注解的，先判断类和方法上是否有@UnLogin注解，有就放行，没有就校验
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler.getClass());
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //在Spring拦截器中获取到Controller类和方法的方式：
        Class<?> beanType = handlerMethod.getBeanType();
        Method method = handlerMethod.getMethod();

        NeedLogin needLogin = method.getAnnotation(NeedLogin.class);
        if(needLogin==null){
            //Controller方法上是否有UnLogin注解
            UnLogin annotation = method.getAnnotation(UnLogin.class);
            if(annotation!=null){
                return true;
            }
            //Controller类上是否有UnLogin注解
            annotation = beanType.getAnnotation(UnLogin.class);
            if(annotation!=null){
                return true;
            }
        }
        //校验是否已经登陆
        Object user = request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        if(user==null){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }
}
